package com.zkkz.boot.campus.utils;

import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import lombok.Getter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
@Component
public class MinioUpload {
    @Value("${minio.endpoint:http://192.168.0.103:9000}")
    @Getter
    private String endpoint;
    @Value("${minio.accessKey:minioadmin}")
    @Getter
    private String accessKey;
    @Value("${minio.secretKey:minioadmin}")
    @Getter
    private String secretKey;
    @Value("${minio.bucketName:wisdom-bucket}")
    @Getter
    private String bucketName;

    public String uploadMinioFile(MultipartFile multipartFile) throws Exception {
        // 初始化MinIO客户端
        MinioClient minioClient = new MinioClient.Builder()
                .endpoint(endpoint)
                .credentials(accessKey, secretKey)
                .build();

        InputStream inputStream = multipartFile.getInputStream();
        String objectName = multipartFile.getOriginalFilename(); // 可选，如果不提供，将使用文件名

        // 构建上传参数
        PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                .bucket(bucketName)
                .object(objectName)
                .contentType(multipartFile.getContentType()) // 设置文件的MIME类型
                .stream(inputStream, inputStream.available(), -1)
                .build();

        // 执行上传操作
        minioClient.putObject(putObjectArgs);
        // 关闭文件输入流
        inputStream.close();
        return endpoint + "/" + bucketName + "/" + objectName;
    }
}